import { HttpClient } from '@angular/common/http';
import { Injectable, Injector, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { ACLService } from '@delon/acl';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { MenuService, SettingsService, TitleService } from '@delon/theme';
import type { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzIconService } from 'ng-zorro-antd/icon';
import { Observable, zip, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { MenusReloadService } from 'src/app/shared/custom_services/MenusReload.service';

import { ICONS } from '../../../style-icons';
import { ICONS_AUTO } from '../../../style-icons-auto';

/**
 * Used for application startup
 * Generally used to get the basic data of the application, like: Menu Data, User Data, etc.
 */
@Injectable()
export class StartupService {
  constructor(
    iconSrv: NzIconService,
    private menuService: MenuService,
    private settingService: SettingsService,
    private aclService: ACLService,
    private titleService: TitleService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private httpClient: HttpClient,
    private injector: Injector,
    private menusReload: MenusReloadService,
    private router: Router
  ) {
    iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
  }

  load(): Observable<void> {
    const tokenData = this.tokenService.get();
    if (!tokenData || !tokenData.token) {
      this.router.navigateByUrl(`/passport/login`);
      return of();
    }
    console.log(tokenData);
    // const uid = tokenData.user.ID;
    return zip(this.httpClient.get(`api/user_detail`), this.httpClient.get(`api/user_menus`)).pipe(
      // 接收其他拦截器后产生的异常消息
      catchError(res => {
        console.warn(`StartupService.load: Network request failed`, res);
        setTimeout(() => this.router.navigateByUrl(`/exception/500`));
        return [];
      }),
      map(([userData, menuData]: NzSafeAny) => {
        console.log(userData.data);
        this.settingService.setUser(userData.data);
        // 菜单刷新
        menuData = this.menusReload.formatAntMenu(menuData.data);
        this.menuService.add(menuData);
        this.aclService.setFull(true);
        // Application information: including site name, description, year...
        this.settingService.setApp({
          name: `ng-alain`,
          description: `Ng-zorro admin panel front-end framework`
        });
        this.titleService.suffix = '';
      })
    );
  }
}
